import * as THREE from 'three'
import { UUIDv4 } from '../../gongJu/gongJu.js'

// 物体
class WuTi {
	bianHao = UUIDv4()
	mingZi = ''
	#shiJianJianTingQi = {} // 事件监听器
	moXing = null
	shiWuTi = true
	
	static quanBuWuTi = [] // 已加载的全部物体

	constructor(moXing = new THREE.Object3D()) {
		this.moXing = moXing
		this.moXing.traverse(wangGe => {
			wangGe.castShadow = true
			wangGe.receiveShadow = true
			wangGe.userData.huoQuWuTi = () => this
		})

		this.tianJiaJianTingQi('zhiZhenJingGuo', () => {})
		this.tianJiaJianTingQi('zhiZhenLiKai', () => {})
	}
	
	// 通过编号获取物体
	static huoQuWuTi(bianHao) {
		for (let i = 0, il = WuTi.quanBuWuTi.length; i < il; i++) {
			let wt = WuTi.quanBuWuTi[i]
			if (wt.bianHao == bianHao) return wt
		}
	}
	// 添加事件监听器
	tianJiaJianTingQi(shiJianLeiXing, hanShu) {
		const shiJianJianTingQi = this.#shiJianJianTingQi;
		shiJianJianTingQi[shiJianLeiXing] ??= []
		if (!shiJianJianTingQi[shiJianLeiXing].includes(hanShu)) shiJianJianTingQi[shiJianLeiXing].push(hanShu)
	}
	// 移除事件监听器
	yiChuJianTingQi(shiJianLeiXing, hanShu) {
		const shiJianJianTingQi = this.#shiJianJianTingQi;
		const hanShuShuZu = shiJianJianTingQi[shiJianLeiXing];

		if (hanShuShuZu !== undefined) {
			const suoYin = hanShuShuZu.indexOf(hanShu);
			if (suoYin !== - 1) hanShuShuZu.splice(suoYin, 1);
		}
	}
	// 触发事件
	/**
	 * @param {Object} shiJian
	 * @param {String} shiJian.leiXing
	 * @param {Object} shiJian.muBiao
	 */
	chuFaShiJian(shiJian) {
		const shiJianJianTingQi = this.#shiJianJianTingQi;
		const hanShuShuZu = shiJianJianTingQi[shiJian.leiXing];

		if (hanShuShuZu !== undefined) {
			shiJian.muBiao = this;
			const shuZu = hanShuShuZu.slice(0);
			for (let i = 0, l = shuZu.length; i < l; i++) {
				shuZu[i].call(this, shiJian);
			}
			shiJian.muBiao = null;
		}
	}
	
}

export {
	WuTi
}